package com.stone.im.geteway.dispather;

import com.stone.im.common.Constants;
import com.stone.im.common.Message;
import com.stone.im.common.Request;
import com.stone.im.common.Response;
import com.stone.im.geteway.tcp.SessionManager;
import com.stone.im.protobuf.proto.AuthenticateResponseProto;
import com.stone.im.protobuf.proto.MessagePushRequestProto;
import com.stone.im.protobuf.proto.MessageSendResponseProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/**
 * 作为与分发系统通信得时间处理组件
 */
public class DispatcherInstanceHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        //断开连接删除实例
        SocketChannel channel = (SocketChannel)ctx.channel();
        String channelId = channel.remoteAddress().getHostName() +":"+channel.remoteAddress().getPort();

        DispatcherInstanceManger dispatcherInstanceManger = DispatcherInstanceManger.getSingleton();
        dispatcherInstanceManger.removeDispatcher(channelId);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        Message message = new Message((ByteBuf) msg);
        System.out.println("收到分发系统发送进来的消息，类型为："+message.getMessageType());
        if (message.getMessageType() == Constants.MESSAGE_TYPE_RESPONSE){

            Response response = message.toResponse();
            //用户认证
            if (response.getRequestType() == Constants.REQUEST_TYPE_AUTHENTICATE){
                AuthenticateResponseProto.AuthenticateResponse authenticateResponse = AuthenticateResponseProto.AuthenticateResponse.parseFrom(response.getBody());
                String uid = authenticateResponse.getUid();

                SessionManager instance = SessionManager.getInstance();
                SocketChannel socketChannel = instance.getClient(uid);
                System.out.println("将响应发送到客户端");
//                socketChannel.writeAndFlush(new Response(response,authenticateResponse.toByteArray()).getBuffer());
                socketChannel.writeAndFlush(new Response(response, authenticateResponse.toByteArray()).getBuffer());
            }else if (response.getRequestType() == Constants.REQUEST_TYPE_SEND_MESSAGE){
                MessageSendResponseProto.MessageSendResponse messageSendResponse = MessageSendResponseProto.MessageSendResponse.parseFrom(response.getBody());
                String senderId = messageSendResponse.getSenderId();
                SessionManager instance = SessionManager.getInstance();
                SocketChannel client = instance.getClient(senderId);
                client.writeAndFlush(response.getBuffer());
            }
        }else if (message.getRequestType() == Constants.MESSAGE_TYPE_REQUEST){
            Request request = message.toRequest();
            if (request.getRequestType() == Constants.REQUEST_TYPE_PUSH_MESSAGE){
                MessagePushRequestProto.MessagePushRequest messagePushRequest = MessagePushRequestProto.MessagePushRequest.parseFrom(request.getBody());
                String receiverId = messagePushRequest.getReceiverId();

                SessionManager instance = SessionManager.getInstance();
                SocketChannel client = instance.getClient(receiverId);
                client.writeAndFlush(request.getBuffer());
            }
        }
    }
}
